package com.hongdee.scm.interior.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.interior.dao.ITScmInteriorDao;
import com.hongdee.scm.interior.entity.TScmInterior;
import com.hongdee.scm.interior.service.ITScmInteriorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 名  称:TScmInteriorServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.interior.service.impl
 * 作  者: 术洪超
 * 日  期:2017-05-14 11:03
 */
@Service
public class TScmInteriorServiceImpl implements ITScmInteriorService {

    String tabName = "t_scm_interior";
    @Autowired
    private ITScmInteriorDao itScmInteriorDao;

    /**
     * @param uid           登录用户 ID
     * @param start         起始记录
     * @param limit         页面大小
     * @param interiorCode  内饰编码
     * @param interiorName  内饰名称
     * @param carSeriesId   车系id
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @Override
    public Map page(String start, String limit, String interiorCode, String interiorName, String carSeriesId, String uid) throws Exception {

        Map map = new HashMap();
        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName);

        if (!StringUtils.isEmpty(interiorCode) && !interiorCode.equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" interior_code like ? ");
            params.add("%" + interiorCode + "%");
        }
        if (!StringUtils.isEmpty(interiorName) && !interiorName.equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" interior_name like ? ");
            params.add("%" + interiorName + "%");
        }
        if (!StringUtils.isEmpty(carSeriesId) && !carSeriesId.equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" car_series_id = ? ");
            params.add(carSeriesId);
        }


        map = this.itScmInteriorDao.page(sql.toString(), params.toArray(), start, limit);
        return map;
    }

    /**
     * @param data 要保存的实体
     * @return Map
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */

    @Override
    public TScmInterior save(TScmInterior data, String uid) throws Exception {
        //id为空时则为添加
        if (data.getId() == null) {
            if (data.getInteriorCode() != null) {
                if (existCode(data.getInteriorCode(), data.getCarSeriesId())) {
                    throw new Exception("内饰代码重复！");
                }
            }
            if (data.getInteriorName() != null) {
                if (existName(data.getInteriorName(), data.getCarSeriesId())) {
                    throw new Exception("内饰名称重复！");
                }
            }
            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());
        } else {
            //id不为空时则为修改
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        //data.setCompanyId(TokenUtil.getCompanyId(uid));
        this.itScmInteriorDao.saveOrUpdate(data);
        return data;
    }

    /**
     * @param uid 登录用户
     * @param id  主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */
    @Override
    public Map info(String id, String uid) throws Exception {

        Common common = new Common();
        Boolean hasWhere = false;
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName);
        if (!StringUtils.isEmpty(id)) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" id = ?");
            params.add(id);
        }
        return this.itScmInteriorDao.info(sql.toString(), params.toArray());
    }

     /*
    判断内饰编码是否存在，用于保存时判断内饰编码是否重复
     */

    private boolean existCode(String interiorCode, String carSeriesId) throws Exception {

        List params = new ArrayList();
        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName + " where car_series_id = ?");
        params.add(carSeriesId);

        if (!interiorCode.isEmpty() && !interiorCode.equals("")) {
            sb.append(" and interior_code = ? ");
            params.add(interiorCode);
        }

        Map map = this.itScmInteriorDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    /*
        判断内饰名称是否存在，用于保存时判断内饰名称是否重复
         */
    private boolean existName(String interiorName, String carSeriesId) throws Exception {
        List params = new ArrayList();
        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName + " where car_series_id = ?");
        params.add(carSeriesId);

        if (!interiorName.isEmpty() && !interiorName.equals("")) {
            sb.append(" and interior_name = ? ");
            params.add(interiorName);
        }

        Map map = this.itScmInteriorDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    /**
     * @return List<Map>
     * @throws Exception
     * @desc 内饰下拉
     * @author 术洪超
     */

    @Override
    public List<Map> combo(String uid, String carSeriesId) throws Exception {

        List param = new ArrayList();
        StringBuffer sb = new StringBuffer();
        //sb.append("select car_series_code from t_bc_car_series where id = ?");
        //param.add(carSeriesId);
        //Map carSeriesCode = this.itScmInteriorDao.info(sb.toString(), param.toArray());

        List params = new ArrayList();
        String sql = " select id,interior_code code,interior_name from " + tabName + " where car_series_id = ? order by create_time desc";
        params.add(carSeriesId);
        List<Map<String, Object>> mapList = this.itScmInteriorDao.list(sql, params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            //temp.put("id", map.get("id"));
            temp.put("value", map.get("code"));
            temp.put("label", map.get("interiorName"));
            resList.add(temp);
        }
        return resList;
    }


    /**
     * 获取全部品牌资源
     */
    private List AllBrand() throws Exception {
        return this.itScmInteriorDao.list("select * from t_bc_brand where status = 1 ");
    }

    /**
     * 查询车系
     */
    private List CarSeries(String bc, String allSeries) throws Exception {

        List params = new ArrayList();

        String sql = "select * from t_bc_car_series where brand_code = ? and type = '0' and res_status = '1' and sale_status = '1'  ";
        params.add(bc);
        if ("0".equals(allSeries)) {
            sql += " or sale_status = '0'";
        }
        return this.itScmInteriorDao.list(sql, params.toArray());
    }

    //构建树
    @Override
    public List buildTree(String allSeries) throws Exception {

        //品牌
        List<Map> brand = AllBrand();
        List<Map> all = new ArrayList<>();

        for (Map temp : brand) {
            Map mapBrand = new HashMap();
            List<Map> series = new ArrayList<>();
            //车系
            List<Map> tempSeries = CarSeries(String.valueOf(temp.get("bCode")), allSeries);
            for (Map tempS : tempSeries) {
                Map mapSeries = new HashMap();
                mapSeries.put("label", tempS.get("carSeriesName"));
                mapSeries.put("value", tempS.get("id"));
                mapSeries.put("code", tempS.get("carSeriesCode"));
                //车系
                mapSeries.put("type", "1");

                mapSeries.put("child", this.buildTreeNodeList(tempS.get("id").toString()));


                series.add(mapSeries);
            }
            //品牌
            mapBrand.put("type", "0");
            mapBrand.put("label", temp.get("bName"));
            mapBrand.put("value", temp.get("bCode"));
            mapBrand.put("child", series);
            all.add(mapBrand);
        }
        return all;
    }

    //内饰列表
    private List carInterior(String carSeriesId) throws Exception {

        List param = new ArrayList();
        StringBuffer sb = new StringBuffer();
       // sb.append("select car_series_code from t_bc_car_series where id = ?");
        //param.add(carSeriesId);
        //Map carSeriesCode = this.itScmInteriorDao.info(sb.toString(), param.toArray());

        List params = new ArrayList();
        params.add(carSeriesId);
        return this.itScmInteriorDao.list("select * from t_scm_interior where car_series_id = ? ", params.toArray());

    }

    /**
     * @param carSeriesId 车系ID
     * @return List<Map>
     * @throws Exception
     * @desc 构建内饰树
     * @author 术洪超
     */
    @Override
    public List<Map> buildTreeNodeList(String carSeriesId) throws Exception {

        List<Map> allInteriors = carInterior(carSeriesId);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allInteriors) {
            Map mapInterior = new HashMap();
            mapInterior.put("label", tempS.get("interiorName"));
            mapInterior.put("value", tempS.get("id"));
            // mapModel.put("code",tempS.get("modelCode"));
            //内饰
            mapInterior.put("type", "2");
            all.add(mapInterior);
        }
        return all;
    }

    /**
     * 是否停用内饰
     * @param interiorIds
     * @param uid
     * @throws Exception
     */
    public void interiorCancel(String[] interiorIds,String uid) throws Exception{

        if(interiorIds==null|| interiorIds.length<=0){
            throw new Exception("请选择内饰");
        }
        List<String> list= new ArrayList<>();
        list = Arrays.asList(interiorIds);
        for (String id:list){
            this.itScmInteriorDao.executeSQL("delete from t_scm_interior where id=?",id);
        }
    }
}
